use rust_admin2_common::{json::JsonPager};
use sqlx::{postgres::{PgRow}};

/// 后台模型基类
pub trait BackendModel<M: serde::ser::Serialize> {

    /// 指定数据表名
    const TABLE_NAME: &'static str = "";

    /// 提定默认要提取的字段
    const FIELDS: &'static str = "";

    /// 默认排序方式
    fn get_order_by() -> &'static str {
        "id DESC"
    }

    /// 默认提取记录数量
    fn get_limit() -> u8 {
        2
    }

    /// 对于单条记录处理
    fn get_row_filter(r: &PgRow) -> M;

    /// 设置分页数据
    fn set_pager<T: serde::ser::Serialize + std::default::Default>(result: Result<Vec<T>, sqlx::error::Error>) -> anyhow::Result<JsonPager<T>> {
        let mut pager: JsonPager<T> = JsonPager::default();
        match result {
            Ok(rows) =>  {
                pager.total = rows.len();
                pager.pages = 1;
                pager.rows = Some(rows);
            },
            Err(_) => {
            }
        };
        return Ok(pager);
    }

    /// 生成查询
    fn get_query() -> String {
        dbg!(format!("SELECT {} FROM {} ORDER BY {} LIMIT {}",
                Self::FIELDS,
                Self::TABLE_NAME,
                Self::get_order_by(),
                Self::get_limit()))
    }
}